package cn.jng.test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：hongwuyang
 * @date ：2022/4/26 17:49
 * @description：sb
 */
public class SBlem {
    public static <T> void uniData(List<T> dataList, String... name)
            throws NoSuchFieldException, IllegalAccessException, InvocationTargetException {

        for (int i = 0; i < dataList.size()-1; i++) {
            ArrayList<Field> currentFields = new ArrayList<>();
            ArrayList<Field> noMatchedFileds = new ArrayList<>();

            getFileds(dataList.get(i).getClass(),currentFields,name);
            for (int j = i+1; j < dataList.size(); j++) {
                getFileds(dataList.get(j).getClass(),noMatchedFileds,name);
                for (int k = 0; k < currentFields.size(); k++) {
                    // 获取class对象
                    Class<?> aClass = dataList.get(i).getClass();
                    Class<?> bClass = dataList.get(j).getClass();
                    // 获取get方法
                    Method method1 = getGetMethod(aClass, currentFields.get(k).getName());
                    Method method2 = getGetMethod(aClass, noMatchedFileds.get(k).getName());

                    Object curent = method1.invoke(dataList.get(i));
                    Object noMatch = method2.invoke(dataList.get(j));

                    if(curent.equals(noMatch) || curent == noMatch){
                        throw new RuntimeException(currentFields.get(k).getName() + "字段重复：" + curent);
                    }
                }
            }
        }
    }

    public static Method getGetMethod(Class objectClass, String fieldName) {
        StringBuffer sb = new StringBuffer();
        sb.append("get");
        sb.append(fieldName.substring(0, 1).toUpperCase());
        sb.append(fieldName.substring(1));
        try {
            return objectClass.getMethod(sb.toString());
        } catch (Exception e) {
        }
        return null;
    }

    public static void getFileds(Class c,ArrayList<Field> fields,String... name) throws NoSuchFieldException {
        for (int i = 0; i < name.length; i++) {
            Field declaredField = c.getDeclaredField(name[i]);
            fields.add(declaredField);
        }
    }

    public static void main(String[] args) throws NoSuchFieldException, InvocationTargetException, IllegalAccessException {
        User user=new User("lem1",12);
        User user1=new User("lem1");
        User user2=new User("le2",13);
       List<User> list = new ArrayList<>();
       list.add(user);
       list.add(user1);
       list.add(user2);
       uniData(list,"name","age");
    }
}
